package dai.samples.shiro.shiro;

import dai.samples.shiro.config.Constants;
import dai.samples.shiro.entity.Permissions;
import dai.samples.shiro.service.UserService;
import dai.samples.shiro.vo.RoleVo;
import dai.samples.shiro.vo.UserVo;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用来认证（AuthenticationInfo）和授权（AuthorizationInfo） 逻辑
 */
@Log4j2
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public CacheManager getCacheManager() {
        return super.getCacheManager();
    }

    /**
     * 授权，给已经认证的用户，添加相关权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //根据用户名去数据库查询用户信息
        UserVo user = userService.getUserByName(name);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (RoleVo role : user.getRoleVos()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;

    }

    /**
     * 认证，用来判断用户身份
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 可以拿到realm的缓存
        Cache<Object, Object> cache = getCacheManager().getCache(Constants.USER_REALM);

        log.info("拿到的缓存类:{}",cache.getClass());

        // 判断是否传递身份标识，本例中为登录名称
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        // 获取用户信息
        String name = authenticationToken.getPrincipal().toString();
        UserVo user = userService.getUserByName(name);
        if (user == null) {
            // 这里返回后会报出对应异常
            return null;
        } else {
            // 这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName());
            return simpleAuthenticationInfo;
        }
    }

}
